<template>
  <div class="qrcode">
    <img :src="base64" alt="" class="qrcode-img" @click="showImage" />
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { uploadBase64 } from '@/api/upload'
function mergeImagesToBase64(images, canvasWidth, canvasHeight) {
  return new Promise((resolve, reject) => {
    // 创建一个动态的canvas元素
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    // 设置canvas的宽高
    canvas.width = canvasWidth
    canvas.height = canvasHeight

    // 按照index排序，确保层级合并
    images.sort((a, b) => a.index - b.index)

    // 加载所有图片，确保按顺序加载
    const loadImagePromises = images.reduce((promiseChain, image) => {
      return promiseChain.then(() => {
        return new Promise((imgResolve, imgReject) => {
          const img = new Image()

          // 检查是否是Base64字符串
          if (image.src.startsWith('data:image/')) {
            img.src = image.src // 直接使用Base64字符串
          } else {
            img.src = image.src // 使用普通图片路径
          }

          img.onload = () => {
            // 绘制图片到canvas
            ctx.drawImage(img, image.left, image.top, image.width, image.height)
            imgResolve()
          }
          img.onerror = () => {
            console.error(`无法加载图片: ${image.src}`)
            imgReject(new Error(`无法加载图片: ${image.src}`))
          }
        })
      })
    }, Promise.resolve()) // 初始化为已解决的 Promise

    // 等待所有图片加载完成
    loadImagePromises
      .then(() => {
        // 导出为Base64
        const base64Image = canvas.toDataURL('image/png')
        resolve(base64Image)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

function isEmpty(str) {
  return `${str}` === 'undefined' || `${str}` === 'null'
}

export default {
  name: 'wx_pages_share_qrcode',
  data() {
    return {
      base64: '',
      qrcode: '',
    }
  },
  async mounted() {
    const { qrcode, link } = this.$route.query
    const qrcodeUrl = await this.generateQRCode(link)
    this.qrcode = isEmpty(qrcode) ? qrcodeUrl : qrcode
    this.mergeImagesToBase64(this.qrcode)
  },
  methods: {
    generateQRCode(link) {
      if (link) {
        return QRCode.toDataURL(link, { errorCorrectionLevel: 'H' })
      }
      return ''
    },
    showImage() {
      if (this.qrcode.startsWith('/')) {
        this.wxSDK.previewImage({
          current: `${window.location.origin}${this.qrcode}`,
          urls: [`${window.location.origin}${this.qrcode}`],
        })
      } else {
        uploadBase64(this.qrcode.replace('data:image/png;base64,', '')).then(
          ({ data }) => {
            this.wxSDK.previewImage({
              current: `${window.location.origin}${data.url}`,
              urls: [`${window.location.origin}${data.url}`],
            })
          }
        )
      }
    },
    async mergeImagesToBase64(qrcode) {
      const width = window.innerWidth
      const height = window.innerHeight
      const images = [
        {
          src: require('@/static/image/sharecode.jpg'),
          width: width,
          height: height,
          left: 0,
          top: 0,
          index: 1,
        },
        {
          src: qrcode,
          width: 140,
          height: 140,
          left: width / 2 - 70,
          top: 165,
          index: 2,
        },
      ]
      mergeImagesToBase64(images, width, height)
        .then((base64) => {
          uploadBase64(base64.replace('data:image/png;base64,', '')).then(
            ({ data }) => {
              this.base64 = data.url
            }
          )
        })
        .catch((error) => {
          console.error(error)
        })
    },
  },
}
</script>

<style lang="less" scoped>
.qrcode {
  width: 100vw;
  height: 100vh;
  background-size: 100% 100%;
  .qrcode-img {
    width: 100%;
    height: 100%;
  }
}
</style>